//
//  LoadingWindow.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/2/14.
//

import SwiftUI
import UIKit

// MARK: - 加载窗口管理类
class LoadingWindow: UIWindow {
    static let shared = LoadingWindow()
    
    private init() {
        // 获取当前场景的尺寸
        guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene else {
            super.init(frame: UIScreen.main.bounds)
            return
        }
        super.init(windowScene: windowScene)
        
        setupWindow()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupWindow() {
        // 窗口配置
        self.windowLevel = .alert + 1  // 置于所有内容之上
        self.backgroundColor = .clear
        self.isHidden = true
        
        // 创建加载视图
        let rootView = LoadView()
        let hosting = UIHostingController(rootView: rootView)
        hosting.view.backgroundColor = .clear
        self.rootViewController = hosting
    }
    
    func show() {
        self.isHidden = false
        self.makeKeyAndVisible()
        // 添加显示动画
        UIView.animate(withDuration: 0.3) {
            self.alpha = 1 // 透明度从 0 变为 1
        }
    }
    
    func hide() {
        // 添加隐藏动画
        UIView.animate(withDuration: 0.3, animations: {
            self.alpha = 0 // 透明度从 1 变为 0
        }) { _ in
            self.isHidden = true
            self.resignKey()
        }
    }
}

// MARK: - 视图修饰符（方便调用）
extension View {
    func loading(isPresented: Bool) -> some View {
        self.modifier(LoadingModifier(isPresented: isPresented))
    }
}

struct LoadingModifier: ViewModifier {
    let isPresented: Bool
    
    func body(content: Content) -> some View {
        content
            .onChange(of: isPresented) { newValue in
                if newValue {
                    LoadingWindow.shared.show()
                } else {
                    LoadingWindow.shared.hide()
                }
            }
    }
}
